<template>
  <div class="contaier">
    <div class="weui_cells_title">创建您的诊疗号：</div>
    <div class="weui_cells weui_cells_form">
      <div class="weui_cell weui_cell_switch">
        <div class="weui_cell_hd weui_cell_primary">将创建的号作为默认号</div>
        <div class="weui_cell_ft">
          <input class="weui_switch" type="checkbox" checked="checked" v-model="asDefault">
        </div>
      </div>
    </div>
    <div class="weui_cells weui_cells_form">
      <div class="weui_cell" :class="{'weui_cell_warn' : invalidName}">
        <div class="weui_cell_hd">
          <label class="weui_label">姓名</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <input class="weui_input" v-model="name" style="padding-left: 15px;" type="text" placeholder="请输入姓名">
        </div>
        <div class="weui_cell_ft">
          <i class="weui_icon_warn"></i>
        </div>
      </div>
      <div class="weui_cell" :class="{'weui_cell_warn' : invalidCertNo}">
        <div class="weui_cell_hd">
          <label class="weui_label">身份证号</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <input class="weui_input" v-model="certNo" style="padding-left: 15px;" type="text" placeholder="请输入身份证号">
        </div>
        <div class="weui_cell_ft">
          <i class="weui_icon_warn"></i>
        </div>
      </div>
      <div class="weui_cell" :class="{'weui_cell_warn' : invalidCellphone}">
        <div class="weui_cell_hd">
          <label class="weui_label">手机号码</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <input class="weui_input" v-model="cellphone" style="padding-left: 15px;" maxlength="11" type="tel" placeholder="请输入手机号码">
        </div>
        <div class="weui_cell_ft">
          <i class="weui_icon_warn"></i>
        </div>
      </div>
      <div class="weui_cell weui_cell_select weui_select_after">
        <div class="weui_cell_hd">
          <label class="weui_label">省份</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <select class="weui_select" v-model="provinceCode">
            <option value="-1" >请选择省份</option>
            <option :value="p.provinceCode + ' || ' + p.provinceName" v-for="p in PList">{{p.provinceName}}</option>
          </select>
        </div>
      </div>
       <div class="weui_cell weui_cell_select weui_select_after">
        <div class="weui_cell_hd">
          <label class="weui_label">城市</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <select class="weui_select" v-model="cityCode">
            <option value="-1" >请选择城市</option>
            <option :value="c.cityCode + ' || ' + c.cityName" v-for="c in CList">{{c.cityName}}</option>
          </select>
        </div>
      </div>
       <div class="weui_cell weui_cell_select weui_select_after">
        <div class="weui_cell_hd">
          <label class="weui_label">县区</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <select class="weui_select" v-model="districtCode">
            <option value="-1" >请选择县区</option>
            <option :value="c.dCode + ' || ' + c.dName" v-for="c in DList">{{c.dName}}</option>
          </select>
        </div>
      </div>
       <div class="weui_cell weui_cell_select weui_select_after">
        <div class="weui_cell_hd">
          <label class="weui_label">街道</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <select class="weui_select" v-model="townCode">
            <option value="-1" >请选择街道</option>
            <option :value="t.tCode + ' || ' + t.tName" v-for="t in TList">{{t.tName}}</option>
          </select>
        </div>
      </div>
      <div class="weui_cell" :class="{'weui_cell_warn' : invalidAddress}">
        <div class="weui_cell_hd">
          <label class="weui_label">详细地址</label>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <input class="weui_input" v-model="address" style="padding-left: 15px;" type="text" placeholder="请输入详细地址">
        </div>
        <div class="weui_cell_ft">
          <i class="weui_icon_warn"></i>
        </div>
      </div>
    </div>
    <div>
      <p style="padding:10px;" class="am-ft-sm am-ft-gray">
        <span class="am-ft-orange"><i class="fa fa-info-circle"></i></span> 温馨提醒：请确保您输入的身份证号码准确无误;如果您还没有办理身份证，可参考户口簿上的身份证号码。
      </p>
    </div>
    <a @click="doNew" href="javascript:;" style="margin:5px 8px;" class="weui_btn weui_btn_primary">确认创建</a>
  </div>
  <partial name="footer-copyright"></partial>
</template>
<style scoped>
.weui_label {
  display: block;
  width: 4em;
}
</style>
<script>
import { showCommonToast, showSuccessToast, hideSuccessToast, addNewCard } from '../../vuex/actions'
import $ from 'jquery'
import _ from 'underscore'
export default {
  name: 'AddNewCardView',
  vuex: {
    actions: {
      showCommonToast,
      addNewCard,
      showSuccessToast,
      hideSuccessToast
    }
  },
  data: function () {
    return {
      asDefault: true,
      name: '',
      certNo: '',
      cellphone: '',
      address: '',
      provinceCode: '-1',
      cityCode: '-1',
      townCode: '-1',
      districtCode: '-1',
      CList: [],
      PList: [],
      DList: [],
      TList: [],
      isFirst: false,
      invalidName: false,
      invalidCertNo: false,
      invalidCellphone: false,
      invalidAddress: false
    }
  },
  methods: {
    doPROVINCE: function () {
      var self = this
      self.cityCode = '-1'
      self.provinceCode = '-1'
      self.districtCode = '-1'
      self.townCode = '-1'
      self.PList = []
      self.CList = []
      self.DList = []
      self.TList = []
      this.$ajax.get('GetPROVINCEInfo', 'Card').then(function (data) {
        self.PList = _.map(data.CITYList, function (val) {
          return {
            provinceCode: val.CODE,
            provinceName: val.NAME
          }
        })
      })
      this.provinceCode = '44 || 广东省'
      this.$ajax.get('GetCityInfo', 'Card', { code: '44' }).then(function (data) {
        self.CList = _.map(data.CITYList, function (val2) {
          return {
            cityCode: val2.CODE,
            cityName: val2.NAME
          }
        })
      })
      this.cityCode = '4406 || 佛山市'
      this.$ajax.get('GetDistrictInfo', 'Card', { code: '4406' }).then(function (data) {
        self.DList = _.map(data.CITYList, function (val2) {
          return {
            dCode: val2.CODE,
            dName: val2.NAME
          }
        })
      })
      this.districtCode = '440606 || 顺德区'
      this.$ajax.get('GetTOWNInfo', 'Card', { code: '440606' }).then(function (data) {
        self.TList = _.map(data.CITYList, function (val2) {
          return {
            tCode: val2.CODE,
            tName: val2.NAME
          }
        })
      })
    },
    doNew: function () {
      if (!this.checkUserInput()) {
        return
      }
      var pcode = this.provinceCode.split(' || ')[0]
      if (pcode === '-1') {
        return// pcode = '44'
      }
      var pname = this.provinceCode.split(' || ')[1]
      var ccode = this.cityCode.split(' || ')[0]
      if (ccode === '-1') {
        return// ccode = '4406'
      }
      var cname = this.cityCode.split(' || ')[1]
      var dcode = this.districtCode.split(' || ')[0]
      if (dcode === '-1') {
        return// dcode = '440606'
      }
      var dname = this.districtCode.split(' || ')[1]
      var tcode = this.townCode.split(' || ')[0]
      if (tcode === '-1') {
        return// return
      }
      var tname = this.townCode.split(' || ')[1]
      var card = {
        isDefault: this.asDefault,
        name: this.name,
        certNo: this.certNo,
        phone: this.cellphone,
        address: this.address,
        provinceCode: pcode,
        provinceName: pname,
        cityCode: ccode,
        cityName: cname,
        townCode: tcode,
        townName: tname,
        districtCode: dcode,
        districtName: dname,
        historyStep: -1
      }

      var self = this
      this.addNewCard(card).then(function (result) {
        if (result.isSucceed) {
          self.showSuccessToast({ msg: result.msg }, false)
          window.setTimeout(function () {
            self.hideSuccessToast()
            if (self.$route.query.nextRoutePath) {
              self.$router.replace({ path: self.$route.query.nextRoutePath })
            } else {
              if (self.historyStep === -1) {
                self.$router.replace({ name: 'portal' })
              } else {
                window.history.go(this.historyStep)
              }
            }
          }, 1600)
        } else {
          self.showCommonToast({ msg: result.msg })
        }
      })
    },
    checkUserInput: function () {
      if (this.name === '') {
        this.invalidName = true
        this.showCommonToast({ msg: '请输入姓名' })
        return false
      }
      if (this.certNo === '') {
        this.invalidCertNo = true
        this.showCommonToast({ msg: '请输入身份证号' })
        return false
      }
      if (this.cellphone === '') {
        this.invalidCellphone = true
        this.showCommonToast({ msg: '请输入手机号码' })
        return false
      }
      if (!(/^1[3|4|5|7|8]\d{9}$/.test(this.cellphone))) {
        this.invalidCellphone = true
        this.showCommonToast({ msg: '手机号码格式不正确！' })
        return
      }
      if (this.address === '') {
        this.invalidAddress = true
        this.showCommonToast({ msg: '请输入联系地址' })
        return false
      }
      // 加权因子
      var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]
        // 身份证验证位值.10代表X
      var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]

      var IdCardValidate =
        function (idCard) {
          // 去掉字符串头尾空格
          idCard = $.trim(idCard.replace(/ /g, ''))
          if (idCard.length === 15) {
            var birth = isValidityBrithBy15IdCard(idCard)
              // 进行15位身份证的验证
            return birth
          } else if (idCard.length === 18) {
            // 得到身份证数组
            var aIdCard = idCard.split('')
            birth = isValidityBrithBy18IdCard(idCard)
              // 进行18位身份证的基本验证和第18位的验证
            if (isTrueValidateCodeBy18IdCard(aIdCard)) {
              return birth
            } else {
              return ''
            }
          } else {
            return ''
          }
        }

      /**
       * 判断身份证号码为18位时最后的验证位是否正确
       */
      var isTrueValidateCodeBy18IdCard =
        function (aIdCard) {
          // 声明加权求和变量
          var sum = 0
          if (aIdCard[17].toString().toLowerCase() === 'x') {
            // 将最后位为x的验证码替换为10方便后续操作
            aIdCard[17] = 10
          }
          for (var i = 0; i < 17; i++) {
            // 加权求和
            sum += Wi[i] * aIdCard[i]
          }
          // 得到验证码所位置
          var valCodePosition = sum % 11
          if (aIdCard[17].toString() === ValideCode[valCodePosition].toString()) {
            return true
          } else {
            return false
          }
        }
        /**
         * 验证18位数身份证号码中的生日是否是有效生日
         */
      var isValidityBrithBy18IdCard =
        function (idCard18) {
          var year = idCard18.substring(6, 10)
          var month = idCard18.substring(10, 12)
          var day = idCard18.substring(12, 14)
          var tempDate = new Date(year, parseFloat(month) - 1, parseFloat(day))
            // 这里用getFullYear()获取年份，避免千年虫问题
          if (tempDate.getFullYear() !== parseFloat(year) || tempDate.getMonth() !== parseFloat(month) - 1 || tempDate.getDate() !== parseFloat(day)) {
            return ''
          } else {
            return year + '-' + month + '-' + day
          }
        }
        /**
         * 验证15位数身份证号码中的生日是否是有效生日
         */
      var isValidityBrithBy15IdCard =
        function (idCard15) {
          var year = idCard15.substring(6, 8)
          var month = idCard15.substring(8, 10)
          var day = idCard15.substring(10, 12)
          var tempDate = new Date(year, parseFloat(month) - 1, parseFloat(day))
            // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getYear()方法
          if (tempDate.getYear() !== parseFloat(year) || tempDate.getMonth() !== parseFloat(month) - 1 || tempDate.getDate() !== parseFloat(day)) {
            return ''
          } else {
            return '19' + year + '-' + month + '-' + day
          }
        }

      if (IdCardValidate(this.certNo) === '') {
        this.invalidCertNo = true
        this.showCommonToast({ msg: '身份证号格式错误,请重新输入' })
        return false
      }

      if (this.cellphone === '') {
        this.invalidCellphone = true
        this.showCommonToast({ msg: '请输入联系电话' })
        return false
      }
      return true
    }
  },
  ready: function () {
    this.doPROVINCE()
    this.$watch('name', function (newVal, oldVal) {
      if (newVal !== '') {
        this.invalidName = false
      }
    })
    this.$watch('certNo', function (newVal, oldVal) {
      if (newVal !== '') {
        this.invalidCertNo = false
      }
    })
    this.$watch('cellphone', function (newVal, oldVal) {
      if (newVal !== '') {
        this.invalidCellphone = false
      }
    })
    this.$watch('address', function (newVal, oldVal) {
      if (newVal !== '') {
        this.invalidAddress = false
      }
    })
    this.$watch('provinceCode', function (val) {
      var self = this
      var vcode = val.split(' || ')[0]
      // if (vcode === '-1') {
      //   vcode = '44'
      // }
      self.cityCode = '-1'
      self.districtCode = '-1'
      self.townCode = '-1'
      self.CList = []
      self.DList = []
      self.TList = []
      this.$ajax.get('GetCityInfo', 'Card', { code: vcode }).then(function (data) {
        self.CList = _.map(data.CITYList, function (val2) {
          return {
            cityCode: val2.CODE,
            cityName: val2.NAME
          }
        })
      })
    })
    this.$watch('cityCode', function (val) {
      var self = this
      var vcode = val.split(' || ')[0]
      // if (vcode === '-1') {
      //   vcode = '4406'
      // }
      self.districtCode = '-1'
      self.townCode = '-1'
      self.DList = []
      self.TList = []
      this.$ajax.get('GetDistrictInfo', 'Card', { code: vcode }).then(function (data) {
        self.DList = _.map(data.CITYList, function (val2) {
          return {
            dCode: val2.CODE,
            dName: val2.NAME
          }
        })
      })
    })
    this.$watch('districtCode', function (val) {
      var self = this
      var vcode = val.split(' || ')[0]
      // if (vcode === '-1') {
      //   vcode = '440606'
      // }
      self.townCode = '-1'
      self.TList = []
      this.$ajax.get('GetTOWNInfo', 'Card', { code: vcode }).then(function (data) {
        self.TList = _.map(data.CITYList, function (val2) {
          return {
            tCode: val2.CODE,
            tName: val2.NAME
          }
        })
      })
    })
  },
  route: {
    activate: function (transition) {
      // 如果是直接跳到该页面的话则点击确定后要跳到portal页
      if (transition.from.name === undefined) {
        this.historyStep = -1
      } else if (transition.from.name === 'addBindingCard') {
        this.historyStep = 2
      } else {
        this.historyStep = 1
      }
      transition.next()
    }
  }
}
</script>
